package com.sunlg.smarthome.data.weather;

import com.sunlg.smarthome.base.C;
import com.sunlg.smarthome.data.remote.MySubscriber;
import com.sunlg.smarthome.utils.JsonUtils;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by sunlg on 2017/5/27.
 */

public class WeatherWrapper {
    private WeatherService weatherService;

    public WeatherWrapper(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(C.API.WEATHER_API)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        weatherService = retrofit.create(WeatherService.class);
    }

    //泛型有待理解

    /**
     *在IO线程上进行网络请求，在UI线程操作数据
     * @return
     */
    <T> Observable.Transformer<T, T> applySchedulers() {
        return new Observable.Transformer<T, T>() {
            @Override
            public Observable<T> call(Observable<T> observable) {
                return observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    public void getNow(MySubscriber<Weather> subscriber, String city){

        weatherService.getNow(city, C.User.KEY)
                .map(new Func1<String, Weather>() {
                    @Override
                    public Weather call(String s) {
                        return JsonUtils.weatherJsonStr2Weather(s);
                    }
                })
                .compose(this.<Weather>applySchedulers())
                .subscribe(subscriber);
    }

    public void search(MySubscriber<City> subscriber, String city){
        weatherService.search(city, C.User.KEY)
                .map(new Func1<String, City>() {
                    @Override
                    public City call(String s) {
                        return JsonUtils.cityJsonStr2City(s);
                    }
                })
                .compose(this.<City>applySchedulers())
                .subscribe(subscriber);
    }
}
